import { Router, Request, Response } from 'express';
import { ScriptService } from '../services/ScriptService';
import { FolderService } from '../services/FolderService';
import Joi from 'joi';
import multer from 'multer';

const router = Router();
const scriptService = new ScriptService();
const folderService = new FolderService();

// 配置文件上传
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 50 // 最多50个文件
  },
  fileFilter: (req, file, cb) => {
    // 只允许SQL文件和文本文件
    const allowedTypes = ['.sql', '.txt', '.json'];
    const fileExt = file.originalname.toLowerCase().substring(file.originalname.lastIndexOf('.'));
    
    if (allowedTypes.includes(fileExt)) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传SQL、TXT、JSON格式的文件'));
    }
  }
});

// 验证中间件
const validateScript = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    name: Joi.string().min(1).max(255).required(),
    content: Joi.string().optional(),
    description: Joi.string().max(1000).optional(),
    tags: Joi.array().items(Joi.string().max(50)).max(20).optional(),
    folder_id: Joi.string().uuid().optional(),
    created_by: Joi.string().max(255).optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateScriptUpdate = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    name: Joi.string().min(1).max(255).optional(),
    content: Joi.string().optional(),
    description: Joi.string().max(1000).optional(),
    tags: Joi.array().items(Joi.string().max(50)).max(20).optional(),
    folder_id: Joi.string().uuid().optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateSearchParams = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    keyword: Joi.string().max(255).optional(),
    tags: Joi.alternatives().try(
      Joi.string(),
      Joi.array().items(Joi.string())
    ).optional(),
    folder_id: Joi.string().uuid().optional(),
    created_by: Joi.string().max(255).optional(),
    limit: Joi.number().integer().min(1).max(100).optional(),
    offset: Joi.number().integer().min(0).optional()
  });

  const { error } = schema.validate(req.query);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateBatchOperation = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    script_ids: Joi.array().items(Joi.string().uuid()).min(1).max(100).required(),
    operation: Joi.string().valid('delete', 'move', 'update_tags').required(),
    data: Joi.object().optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

// ==================== CRUD操作 ====================

// 创建脚本
router.post('/', validateScript, async (req: Request, res: Response): Promise<void> => {
  try {
    const script = await scriptService.createScript(req.body);
    res.status(201).json({
      success: true,
      message: '脚本创建成功',
      data: script
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '创建脚本失败',
      error: error.message
    });
  }
});

// 获取脚本列表（支持搜索和过滤）
router.get('/', validateSearchParams, async (req: Request, res: Response): Promise<void> => {
  try {
    const {
      keyword,
      tags,
      folder_id,
      created_by,
      limit = 20,
      offset = 0
    } = req.query;

    // 处理tags参数
    let tagsArray: string[] | undefined;
    if (tags) {
      if (typeof tags === 'string') {
        tagsArray = tags.split(',').map(tag => tag.trim());
      } else if (Array.isArray(tags)) {
        tagsArray = tags as string[];
      }
    }

    const result = await scriptService.searchScripts({
      keyword: keyword as string,
      tags: tagsArray,
      folder_id: folder_id as string,
      created_by: created_by as string,
      limit: Number(limit),
      offset: Number(offset)
    });

    res.json({
      success: true,
      message: '获取脚本列表成功',
      data: result
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取脚本列表失败',
      error: error.message
    });
  }
});

// 获取所有标签
router.get('/tags', async (req: Request, res: Response): Promise<void> => {
  try {
    const tags = await scriptService.getAllTags();
    
    res.json({
      success: true,
      message: '获取标签列表成功',
      data: tags
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取标签列表失败',
      error: error.message
    });
  }
});

// 获取单个脚本详情
router.get('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const script = await scriptService.getScript(id);
    
    if (!script) {
      res.status(404).json({
        success: false,
        message: '脚本不存在'
      });
      return;
    }

    res.json({
      success: true,
      message: '获取脚本详情成功',
      data: script
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取脚本详情失败',
      error: error.message
    });
  }
});

// 更新脚本
router.put('/:id', validateScriptUpdate, async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const script = await scriptService.updateScript(id, req.body);
    
    res.json({
      success: true,
      message: '脚本更新成功',
      data: script
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新脚本失败',
      error: error.message
    });
  }
});

// 删除脚本
router.delete('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    await scriptService.deleteScript(id);
    
    res.json({
      success: true,
      message: '脚本删除成功'
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '删除脚本失败',
      error: error.message
    });
  }
});

// ==================== 脚本管理操作 ====================

// 移动脚本到其他文件夹
router.patch('/:id/move', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { folder_id } = req.body;
    
    const script = await scriptService.moveScript(id, folder_id);
    
    res.json({
      success: true,
      message: '脚本移动成功',
      data: script
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '移动脚本失败',
      error: error.message
    });
  }
});

// 复制脚本
router.post('/:id/copy', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { name, folder_id } = req.body;
    
    const script = await scriptService.copyScript(id, { name, folder_id });
    
    res.status(201).json({
      success: true,
      message: '脚本复制成功',
      data: script
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '复制脚本失败',
      error: error.message
    });
  }
});

// 更新脚本标签
router.patch('/:id/tags', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { tags } = req.body;
    
    if (!Array.isArray(tags)) {
      res.status(400).json({
        success: false,
        message: 'tags必须是数组格式'
      });
      return;
    }
    
    await scriptService.updateScriptTags(id, tags);
    
    res.json({
      success: true,
      message: '脚本标签更新成功'
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新脚本标签失败',
      error: error.message
    });
  }
});

// ==================== 批量操作 ====================

// 批量操作脚本
router.post('/batch', validateBatchOperation, async (req: Request, res: Response): Promise<void> => {
  try {
    const { script_ids, operation, data } = req.body;
    let result;
    
    switch (operation) {
      case 'delete':
        result = await scriptService.batchDeleteScripts(script_ids);
        break;
      case 'move':
        if (!data || !data.hasOwnProperty('folder_id')) {
          res.status(400).json({
            success: false,
            message: '移动操作需要提供folder_id'
          });
          return;
        }
        result = await scriptService.batchMoveScripts(script_ids, data.folder_id);
        break;
      case 'update_tags':
        if (!data || !Array.isArray(data.tags)) {
          res.status(400).json({
            success: false,
            message: '更新标签操作需要提供tags数组'
          });
          return;
        }
        result = await scriptService.batchUpdateTags(script_ids, data.tags);
        break;
      default:
        res.status(400).json({
          success: false,
          message: '不支持的批量操作类型'
        });
        return;
    }
    
    res.json({
      success: true,
      message: `批量${operation === 'delete' ? '删除' : operation === 'move' ? '移动' : '更新标签'}成功`,
      data: result
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '批量操作失败',
      error: error.message
    });
  }
});

// ==================== 导入导出 ====================

// 导入脚本
router.post('/import', upload.array('files'), async (req: Request, res: Response): Promise<void> => {
  try {
    const files = req.files as Express.Multer.File[];
    const { folder_id, created_by } = req.body;
    
    if (!files || files.length === 0) {
      res.status(400).json({
        success: false,
        message: '请选择要导入的文件'
      });
      return;
    }
    
    const result = await scriptService.importScripts(files, {
      folder_id,
      created_by
    });
    
    res.status(201).json({
      success: true,
      message: '脚本导入成功',
      data: result
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '导入脚本失败',
      error: error.message
    });
  }
});

// 导出脚本
router.post('/export', async (req: Request, res: Response): Promise<void> => {
  try {
    const { script_ids, format = 'zip' } = req.body;
    
    if (!Array.isArray(script_ids) || script_ids.length === 0) {
      res.status(400).json({
        success: false,
        message: '请选择要导出的脚本'
      });
      return;
    }
    
    const result = await scriptService.exportScripts(script_ids, format);
    
    // 设置下载响应头
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', `attachment; filename="scripts_export_${Date.now()}.zip"`);
    
    res.send(result.buffer);
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '导出脚本失败',
      error: error.message
    });
  }
});

// ==================== 统计和分析 ====================

// 获取脚本统计信息
router.get('/stats/overview', async (req: Request, res: Response): Promise<void> => {
  try {
    const { user_id } = req.query;
    
    const stats = await scriptService.getUserScriptStats(user_id as string || 'system');
    
    res.json({
      success: true,
      message: '获取脚本统计成功',
      data: stats
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取脚本统计失败',
      error: error.message
    });
  }
});

export default router;